# -*- coding:utf-8 -*-
"""
@Time : 2021/1/10 14:44
@Author: langengel
@Des: 角色管理
"""
from typing import Optional
from fastapi import Request, Query
from application.service.common import rule_tree
from saas.response.BaseResponse import success, fail, res_antd
from models.saas import Role, Service, Rule
from validator.service import CreateRole, UpdateRole, ChangeStatus, SetScopes


async def role_list(
        req: Request,
        role_status: Optional[bool] = Query(None),
        pageSize: int = Query(10),
        current: int = Query(1),
        role_name: str = Query(None),
):
    """
    角色搜索查询
    :param req:
    :param role_status: 角色状态
    :param pageSize: 每页条数
    :param current: 当前页码
    :param role_name: 角色名称
    :return: res_ant
    """
    # 提取查询条件
    query = {}
    if role_status is not None:
        query["role_status"] = role_status
    if role_name:
        query["role_name"] = role_name

    roles = Role().filter(**query, service=req.state.sid).all()
    total = await roles.count()
    roles_list = await roles.limit(pageSize).offset(pageSize * (current - 1)).values(
        "create_time", "id", "role_desc", "service_id", "update_time", "role_name", "role_status"
    )
    # 这个参数不为空 查询所有对应状态

    for role in roles_list:
        role.update({"key": role["id"]})

    return res_antd(data=roles_list, total=total)


async def del_role(req: Request, role_id: int):
    """
    角色删除
    :param req:
    :param role_id:
    :return:
    """
    res = await Role().filter(pk=role_id, service=req.state.sid).delete()
    if res:
        return success(msg="删除成功")
    else:
        return fail(msg="删除失败")


async def create_role(req: Request, post: CreateRole):
    """
    角色创建
    :param req: Request
    :param post: CreateRole
    :return: boolean
    """

    service = await Service().get_or_none(id=req.state.sid)
    add_role = await Role().create(
        role_status=post.role_status,
        service=service,
        role_name=post.role_name,
        role_desc=post.role_desc
    )

    if add_role:
        return success(msg="创建成功", data=add_role)

    return fail(msg="创建失败")


async def update_role(req: Request, post: UpdateRole):
    """
    角色基本信息更新
    :param req:
    :param post:
    :return:
    """
    role = await Role().get_or_none(id=post.role_id, service=req.state.sid)
    await role.update_from_dict(post.dict()).save()
    return success(msg="更新成功")


async def change_status(req: Request, post: ChangeStatus):
    """
    角色状态修改
    :param req: request
    :param post: ChangeStatus
    :return:
    """

    role = await Role().get_or_none(id=post.role_id, service=req.state.sid)
    await role.update_from_dict({"role_status": post.role_status}).save()
    return success(msg="更新成功")


async def sys_rule():
    """
    服务商全部权限
    :return:
    """
    rule_list = await Rule().filter(is_check=1).all().values("id", "rule_name", "scopes", "parent_id")
    for rule in rule_list:
        rule["title"] = rule.pop("rule_name")
        rule["key"] = rule["id"]
        rule["value"] = rule["id"]
        rule["pId"] = rule.pop("parent_id")

    data = rule_tree(rule_list, 0)

    return success(data=data, msg="服务商权限")


async def get_role_rule(req: Request, role_id: int):
    """
    当前角色权限
    :param req: Request
    :param role_id: 角色ID
    :return:
    """
    role = await Role().get_or_none(id=role_id, service=req.state.sid)
    rules = await role.rules.filter(is_check=1, is_menu__not=1).all().values('id', 'rule_name')
    role_rules = []
    for rule in rules:
        role_rules.append(rule["id"])

    return success(data=role_rules, msg="当前角色权限")


async def set_scopes(req: Request, post: SetScopes):
    """
    角色权限分配
    :param req: Request
    :param post: SetScopes
    :return:
    """
    # 删除当前角色全部权限
    role = await Role().get(id=post.role_id, service=req.state.sid)

    await role.rules.clear()

    # 三级权限
    three = await Rule().filter(id__in=post.scopes).all()
    two = []
    for rule in three:
        two.append(rule.parent_id)

    # 二级权限
    two_rules = await Rule().filter(id__in=two).all()
    one = []
    for rule in two_rules:
        one.append(rule.parent_id)

    # 一级权限
    one_rules = await Rule().filter(id__in=one).all()

    all_rule = three + two_rules + one_rules

    if all_rule:
        await role.rules.add(*set(all_rule))

    return success(msg="更新成功")
